package com.fire.user.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fire.core.mode.TMitUserToken;
import com.fire.core.service.ITMitServiceDicBaseServices;
import com.fire.core.util.Md5Util;
import com.fire.core.util.ToolUtil;
import com.fire.user.constants.ErrorCodeConstants;
import com.fire.user.dao.UsersMapper;
import com.fire.user.model.*;
import com.fire.user.model.TMitChannel;
import com.fire.user.model.TMitRecordLogin;
import com.fire.user.service.ITMitChannelService;
import com.fire.user.service.ITMitRecordLoginService;
import com.fire.user.service.IUserServiceTwo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * <p>
 * 用户表 新服务实现类
 * </p>
 *
 * @author raoyuxing
 * @since 2018-08-16
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceTwoImpl extends ServiceImpl<UsersMapper, User> implements IUserServiceTwo {
	private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceTwoImpl.class);

	@Autowired
	private UsersMapper usersMapper;
	@Autowired
	private ITMitChannelService channelService;
	@Autowired
	private ITMitRecordLoginService recordLoginService;
	@Autowired
	private ITMitServiceDicBaseServices baseService;
	@Autowired
	RedisTemplate redisTemplate;

	/**
	 * 用户登录
	 *
	 * @param users
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> loginUser(User users,String TUrl) throws Exception {

		Integer tokenOutTime = Integer.valueOf(baseService.getBaseByBkey("GUANGDONG_TOKENOUTTIME"));

		Map recordMap = new HashMap();
		recordMap.put("resourceid",users.getResourceid());
		Map<String, Object> map = new HashMap<>(10);
		if(ToolUtil.isEmpty(users.getChannelid())) {
			users.setChannelid(1);
		}
		TMitChannel mitChannel = channelService.selectById(users.getChannelid());
		if((ToolUtil.isNotEmpty(mitChannel) && mitChannel.getChannelstatus()!= 1)|| ToolUtil.isEmpty(mitChannel)) {
			map.put("status", "2004");
			map.put("message", "该渠道维护中，请联系客服人员！");
			map.put("tips", "[2004]该渠道维护中，请联系客服人员！");
			return map;
		}
		// 如果是密码不为空,为密码登录
		if (ToolUtil.isNotEmpty(users.getPasswd())) {
			// 密码加密
			String pwd = Md5Util.encrypt(users.getPasswd());
			users.setPasswd(pwd);
		}

		User user = usersMapper.selectByPhone(users.getPhone());
		if(ToolUtil.isEmpty(user)){
			recordMap.put("TUrl",TUrl);
			user = addUser(users,recordMap);
		}

		TMitUserToken userToken = setTokenRedis(user);
		//设置userId缓存时间
		redisTemplate.opsForValue().set(userToken.getUserid().toString(), userToken.getToken(), tokenOutTime, TimeUnit.MINUTES);
		//更新token时间
		redisTemplate.opsForValue().set(userToken.getToken(), userToken, tokenOutTime, TimeUnit.MINUTES);

		if (ToolUtil.isNotEmpty(user.getResourcetype()) && user.getResourcetype() == 6) {
            recordMap.put("TUrl",TUrl);
			addRecordLogin(user, "login", recordMap);
		}else {
			addRecordLogin(user,"login",recordMap);
		}
		map.put("status", ErrorCodeConstants.SUCCESS);
		map.put("message", "登录成功");
		map.put("tips", "登录成功");
		map.put("turl",replaceUrl(TUrl));
		map.put("token", userToken.getToken());
		map.put("snsapi",mitChannel.getSnsapi());
		map.put("user", user);
		LOGGER.info("登录成功..............");
		return map;
	}

	/**
	 * 添加用户
	 *
	 * @param users
	 * @throws Exception
	 */
	@Override
	public User addUser(User users,Map recordMap ){
		if(ToolUtil.isEmpty(users.getChannelid())) {
			users.setChannelid(1);
		}
		users.setCreatetime(new Date());
		// 如果是密码不为空
		if (ToolUtil.isNotEmpty(users.getPasswd())) {
			// 密码加密
			String pwd = Md5Util.encrypt(users.getPasswd());
			users.setPasswd(pwd);
		}
		TMitChannel mitChannel = channelService.selectById(users.getChannelid());
		if(ToolUtil.isEmpty(users.getAliasname())) {
			users.setAliasname("ybt_"+users.getPhone());
		}
		if(ToolUtil.isEmpty(users.getSex())){
			users.setSex(9);
		}
		usersMapper.insert(users);
		if(ToolUtil.isNotEmpty(users.getResourcetype()) && users.getResourcetype() == 6){
			addRecordLogin(users,"verifyode",recordMap);
		}else {
			recordMap.remove("TUrl");
			addRecordLogin(users,"verifyode",recordMap);
		}

		return users;
	}

	/**
	 * 设置token缓存
	 * @param user
	 * @return
	 * @throws ParseException
	 */
	public TMitUserToken setTokenRedis(User user) throws ParseException {
		// 设置token
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); // 设置日期格式
		String date = df.format(new Date());
		String token = user.getUserid().toString() + date;
		token=Md5Util.encrypt(token);
		TMitUserToken userToken = new TMitUserToken();
		if(ToolUtil.isEmpty(user.getChannelid())){
			user.setChannelid(1);
		}
		TMitChannel mitChannel = channelService.selectById(user.getChannelid());
		userToken.setToken(token);
		userToken.setUserid(user.getUserid());
		userToken.setChannelid(user.getChannelid());
		userToken.setChannelname(mitChannel.getChannelname());
		userToken.setResourceid(user.getResourceid());
		userToken.setResourcename(user.getResourcename());
		userToken.setResourcetype(user.getResourcetype());
		userToken.setAliasname(user.getAliasname());
		userToken.setPhone(user.getPhone());
		if (!("").equals(user.getWxid()) || null != user.getUserid()) {
			userToken.setLogintype(1);
		} else {
			userToken.setLogintype(0);
		}
		return userToken;
	}

	/**
	 * 记录登录信息
	 * @param users
	 *  name :注册  登录
	 */
	@Override
	public void addRecordLogin(User users,String name,Map recordMap) {
		TMitRecordLogin recordLogin = new TMitRecordLogin();
		recordLogin.setChanelid(users.getChannelid());
		recordLogin.setChanelname(users.getChannelname());
		recordLogin.setCreatetime(new Date());
		if(!"loginOut".equals(name)) {
			recordLogin.setLogintime(new Date());
		}
		recordLogin.setLogintype("2");
		recordLogin.setUserid(users.getUserid().toString());
		recordLogin.setWho(users.getAliasname());
		recordLogin.setPhone(users.getPhone());
		recordLogin.setResourceid(String.valueOf(recordMap.get("resourceid")));
		recordLogin.setResourcetype(6);
		if("verifyode".equals(name)){
			recordLogin.setWay(2);
		}else if("login".equals(name)){
			recordLogin.setWay(1);
		}else if("loginOut".equals(name)){
			recordLogin.setWay(0);
		}
		if (ToolUtil.isNotEmpty(recordMap.get("TUrl"))){
			recordLogin.setExtral(String.valueOf(recordMap.get("TUrl")));
		}
		recordLoginService.insert(recordLogin);
	}


	protected String replaceUrl(String url){
		String newurl = "";
		String ybtUrl = baseService.getBaseByBkey("GUANGDONG_YBTURL");
		if (url.contains(ybtUrl)){
			newurl = url.replace(ybtUrl,"");
		}else {
			newurl = url;
		}
		return newurl;
	}

}

